package cate.game.activity.base.core;

import cate.common.table.activity.RegisterActivityBaseRow;
import cate.common.table.pay.PayItemRow;
import cate.common.util.GameResult;
import cate.common.util.TimeTool;
import cate.common.util.must_call_super.MustCallSuper;
import cate.game.activity.config.ActivityBaseCfgPO;
import cate.game.activity.msg.ActivityCloseUpdate;
import cate.game.role.Role;
import cate.game.role.RoleDependent;
import com.fasterxml.jackson.annotation.JsonIgnore;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;

import java.util.Collections;
import java.util.Optional;

@NoteClass("活动个人数据")
public class RoleActivitySingle extends RoleDependent {
    @NoteField("功能ID")
    public int funcId;
    @NoteField("基础配置")
    public ActivityBaseCfgPO base;

    @Override
    @MustCallSuper
    public void initialize(Role role) {
        super.initialize(role);
        if (base == null) {
            base = ActivityBaseCfgPO.EMPTY(funcId);
        }
        if (this.getClass() == RoleActivitySingle.class) {
            logger.info("异常类找到了，funcId={}", funcId);
        }
    }

    @Override
    @MustCallSuper
    public void onEnter() {
        loadBase(true);
    }

    public final void onEnterSafe() {
        try {
            onEnter();
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    @Override
    @MustCallSuper
    public void onDaySpan(boolean silence) {
        // 注册日活动原则上在跨天时才会加载---老设定
        loadBase(false);
    }

    @Override
    public void onMonthSpan(boolean silence) {
        super.onMonthSpan(silence);
    }

    /**
     * 数据初始化
     *
     * @param funcId 功能ID
     */
    public void init(int funcId) {
        this.funcId = funcId;
        this.base = ActivityBaseCfgPO.EMPTY(funcId);
    }

    /**
     * 从全服活动处理中加载最新活动时间
     */
    public void loadBase(boolean silence) {
        ActivityBaseCfgPO cfgPO = null;
        ActivityHandler<?, ?> handler = role.getGame().activityGlobal.getHandler(funcId);
        if (handler != null) {
            cfgPO = handler.getGlobalData().base.copy();
        }
        if (cfgPO == null || !cfgPO.active()) {
            cfgPO = loadRegister();
        }
        if (cfgPO == null) {
            cfgPO = ActivityBaseCfgPO.EMPTY(funcId);
        }
        setActivityConf(cfgPO, silence);
    }

    /**
     * 设置新的时间配置
     *
     * @param currentCfg 新的时间配置
     */
    private void setActivityConf(ActivityBaseCfgPO currentCfg, boolean silence) {
        if (currentCfg.eq(base)) {
            base.readTime(currentCfg);
            return;
        }
        if (base.active()) {
            if (!silence) {
                role.sendNow(new ActivityCloseUpdate(Collections.singletonList(funcId)));
            }
            onRoleEnd();
        }
        if (currentCfg.active()) {
            base = currentCfg;
        } else {
            base = ActivityBaseCfgPO.EMPTY(funcId);
        }
        if (base.active()) {
            try {
                excelCheck();
            } catch (Exception e) {
                logger.error("活动excel check失败！功能id{},活动id:{},配置id:{}", funcId, base.activityId, base.configTid, e);
            }
            onRoleOpen();
            if (!silence) {
                initSend();
            }
        }
    }

    /**
     * 加载注册日配置
     */
    private ActivityBaseCfgPO loadRegister() {
        for (RegisterActivityBaseRow row : role.getGame().table.activity.register.getList()) {
            if (row.funcId != funcId) {
                continue;
            }
            long startTime = TimeTool.calTimeStamp(role.getStatus().createTime, row.startDay);
            long endTime = TimeTool.calTimeStamp(role.getStatus().createTime, row.endDay);
            if (startTime > game().time.now() || endTime < game().time.now()) {
                continue;
            }
            ActivityBaseCfgPO cc = new ActivityBaseCfgPO();
            cc.activityId = row.activityId;
            cc.funcId = funcId;
            cc.configTid = row.configId;
            cc.startTime = startTime;
            cc.endTime = endTime;
            return cc;
        }
        return null;
    }

    /**
     * 活动是否开启
     */
    public boolean enable() {
        return Optional.ofNullable(base).map(ActivityBaseCfgPO::active).orElse(false);
    }

    /**
     * 获取功能ID
     */
    public final int funcId() {
        return Optional.ofNullable(base).map(b -> b.funcId).orElse(0);
    }

    /**
     * 获取活动ID
     */
    public int activityId() {
        return Optional.ofNullable(base).map(b -> b.activityId).orElse(0);
    }

    /**
     * 获取配置ID
     */
    public final int configTid() {
        return Optional.ofNullable(base).map(b -> b.configTid).orElse(0);
    }

    /**
     * 获取当前天数
     */
    @JsonIgnore
    public final int getCurrentDay() {
        if (base == null || base.startTime == 0) {
            return 0;
        }
        return TimeTool.getDistanceDays(base.startTime, game().time.now()) + 1;
    }

    /**
     * 玩家活动开启
     */
    public void onRoleOpen(){

    }

    /**
     * 玩家活动结束
     */
    public void onRoleEnd(){

    }

    /**
     * 是否需要发送初始消息
     * <p>
     * 特殊的活动需要在关闭的时候发送消息可以重写此接口
     */
    public boolean needInitSend() {
        return enable();
    }

    /**
     * 初始发包
     */
    public void initSend(){

    }

    /**
     * 配置检测
     */
    public void excelCheck(){

    }

    /**
     * 是否支持支付
     *
     * @param pir 支付配置
     */
    public GameResult<Void> allowPay(PayItemRow pir) {
        GameResult<Void> r = new GameResult<>();
        return r.fail("支付失败");
    }

    /**
     * 支付成功回调
     *
     * @param pir 支付配置
     */
    public void onPaySuccess(PayItemRow pir) {

    }

    /**
     * 循环
     */
    public void tick() {

    }

    /**
     * 合服处理
     */
    public void onMergeSettle() {

    }

    @JsonIgnore
    public long startTime() {
        return base.startTime;
    }

    @JsonIgnore
    public long endTime() {
        return base.endTime;
    }
}
